import {reqSendCode,reqRegister,reqLogin,reqUserInfo,reqlogout} from '@/api'
import { setToken,getToken,clearToken } from '@/utils/token'
const state = {
    data:'',
    token:getToken(),
    userInfo:{}
}
const actions = {
    // 验证码
   async getSendCode({commit},phone){
       console.log()
        let result = await reqSendCode(phone);
        if(result.code == 200){
            commit('GETSENDCODE',result.data)
            return 'ok'
        }else{
            return Promise.reject(result.message)
        }
    },
    // 注册用户
    async succeedRegister({commit},{phone,code,password}){
        let result = await reqRegister(phone,code,password);
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(result.message)
        }
    },
    // 用户登录
    async login({commit},{phone,password}){
        let result = await reqLogin(phone,password);
        if(result.code == 200){
            commit('LOGIN',result.data.token)
            setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(result.message)
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
        let result =await reqUserInfo();
        if(result.code == 200){
            commit('GETUSERINFO',result.data)
        }
    },
    // 用户取消登录
    async loginOut({commit}){
        let result = await reqlogout();
        if(result.code == 200){
            commit('LOGINOUT')
        }
    }
}
const mutations ={
    GETSENDCODE(state,sendCode){
        state.data = sendCode
    },
    LOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    LOGINOUT(state){
        state.token = "";
        state.userInfo = {};
        clearToken();
    }
}
const getters = {}
export default {
    state,
    actions,
    mutations,
    getters
}